import './style.css'
import { files } from './files';
import { WebContainer } from '@webcontainer/api';

const reportOutput = (output: string) => {
  outputPanel.textContent += " \n" + (output)
}

let webcontainerInstance: any;
let registry = ['config', "set", "registry", "https://registry.npmmirror.com/"]





window.addEventListener('load', async () => {
  //读取文件内容
  editor.value = files.file.directory['index.js'].file.contents;


  // 启动容器
  webcontainerInstance = await WebContainer.boot();
  // 装载文件
  await webcontainerInstance.mount(files.file.directory);
  // await webcontainerInstance.mount(files);


  //    ^ is an array of strings
  const exitCode = await installDependencies();
  if (exitCode !== 0) {
    throw new Error('安装失败');
  };
  // const process = await webcontainerInstance.spawn("node", ["-v"])
  // process.output.pipeTo(new WritableStream({
  //   write: (chunk) => {
  //     reportOutput(`Process output: ${chunk}`)
  //   }
  // }))

  // 启动应用
  startDevServer();
  // showvalue()

  //监听内容变化
  editor.addEventListener('input', (e) => {
    // console.log(e.currentTarget.value);
    writeIndexJS(e.currentTarget.value);
  });
});



// async function showvalue () {
//   const showdir = await webcontainerInstance.spawn('ls', ['src', '-l']);
//   showdir.output.pipeTo(new WritableStream({
//     write (data) {
//       terEl.value = data;
//     }
//   }));

// }



async function writeIndexJS(content: string) {
  await webcontainerInstance.fs.writeFile('index.js', content);
};

// pnpm config set registry https://registry.npmmirror.com/

async function installDependencies() {
  // 设置国内镜像加速
  webcontainerInstance.spawn('pnpm', registry);
  // Install dependencies
  const installProcess = await webcontainerInstance.spawn('pnpm', ["i"]);
  installProcess.output.pipeTo(new WritableStream({
    write(data) {
      reportOutput(data.toString());
    }
  }));
  // Wait for install command to exit
  return installProcess.exit;
}



async function startDevServer() {
  // Run `npm run start` to start the Express app
  await webcontainerInstance.spawn('yarn', ['start']);

  // Wait for `server-ready` event
  webcontainerInstance.on('server-ready', (port, url) => {
    output.src = url;
    // output.textContent = port
  });
}

